﻿// This source file is part of WallpaperControl, a tool for automatic changing 
// of the desktop wallpaper.
// 
// Visit http://www.wallpaper-control.xe.cx/ and 
// http://wpcontrol.codeplex.com/ for more.
//
// Copyright (c) 2009 Niklas Kroll
//
// Licensed under the GPLv2.
// See http://www.gnu.org/licenses/gpl-2.0.html for details.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.


using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;

namespace wpControl1
{
    /// <summary>
    /// The ControlPanel form.
    /// </summary>
    public partial class ControlPanel : Form
    {
        System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ControlPanel));

        public ControlPanel()
        {
            this.InitializeComponent();
            this.InitStyleNameStack();
        }

        private void InitStyleNameStack()
        {
            // Initialize style name list
            this.StyleNames = new List<string>();

            this.StyleNames.Insert(0, Program.LanguageManager.GetString("Zoom_CenteredText"));
            this.StyleNames.Insert(0, Program.LanguageManager.GetString("Zoom_TiledText"));
            this.StyleNames.Insert(0, Program.LanguageManager.GetString("Zoom_StretchedText"));
            this.styleBindingSource.DataSource = this.StyleNames;
        }

        private void buttonAdd_Click(object sender, EventArgs e)
        {
            // Add a new image
            Program.ImageManager.AddImage();
            // Keep buttons-up-to-date
            this.UpdateImageButtons();
        }

        private void buttonDelete_Click(object sender, EventArgs e)
        {
            // Remove selected image
            Program.ImageManager.RemoveImage();
            // Keep buttons up-to-date
            this.UpdateImageButtons();
        }

        private void listBoxImages_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Update button status
            this.UpdateImageButtons();
            // Load the selected style for selected image
            Program.ZoomStyleManager.LoadStyle();
        }

        private void buttonUp_Click(object sender, EventArgs e)
        {
            // Move selected image up
            Program.ImageManager.MoveImageUp();
        }

        private void buttonDown_Click(object sender, EventArgs e)
        {
            // Move selected image down
            Program.ImageManager.MoveImageDown();
        }

        private void buttonPreview_Click(object sender, EventArgs e)
        {
            // Open preview
            Program.ImageManager.PreviewImage();
        }

        private void buttonOK_Click(object sender, EventArgs e)
        {
            // Save start mode
            Program.StartManager.StoreStartMode();
            // Save configuration 
            Program.ConfigManager.SaveConfig();
            // Close ControlPanel
            this.Close();
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            // Close ControlPanel - don't save settings
            this.Close();
        }

        private void buttonShowNow_Click(object sender, EventArgs e)
        {
            // Set selected image as wallpaper now
            Program.WallpaperManager.SetSelectedWallpaper();
        }

        private void radioButtonTime_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButtonTime.Checked)
            {
                // Change condition type
                Program.ConditionManager.CondType = 1;
                // Disable controls for interval
                radioButtonInterval.Checked = false;
                comboBoxInterval.Enabled = false;
                // Enable timepicker for time condition
                timePicker.Enabled = true;
            }
        }

        private void radioButtonInterval_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButtonInterval.Checked)
            {
                // Change condition type
                Program.ConditionManager.CondType = 2;
                // Disable control for time condition
                radioButtonTime.Checked = false;
                timePicker.Enabled = false;
                // Enable dropdown for interval
                comboBoxInterval.Enabled = true;
            }
        }

        private void buttonPrevious_Click(object sender, EventArgs e)
        {
            // Set previous wallpaper as current
            Program.WallpaperManager.SetPreviousWallpaper();
        }

        private void buttonNext_Click(object sender, EventArgs e)
        {
            // Set next wallpaper as current
            Program.WallpaperManager.SetNextWallpaper();
        }

        private void linkLabelWebsite_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            // Open project page with standard browser
            Process.Start("http://wpcontrol.codeplex.com/");
        }

        private void checkBoxLoop_CheckedChanged(object sender, EventArgs e)
        {
            // A balloon tip for repeating info can't be shown if repeating is 
            // disabled.
            // Check if repeating is enabled
            if (checkBoxLoop.Checked)
            {
                // If yes enable possibility to enable balloon tip
                checkBoxRepeatingTip.Enabled = true;
            }
            else
            {
                // If not disable possibility and deselect it
                checkBoxRepeatingTip.Enabled = false;
                checkBoxRepeatingTip.Checked = false;
            }

            // Save setting
            Program.SettingsManager.LoopWallpapers = this.checkBoxLoop.Checked;
        }

        /// <summary>
        /// Updates the ControlPanel so that the form status matches the restored 
        /// settings from the config files.
        /// </summary>
        internal void RestoreValues()
        {
            this.LoadImageList();
            this.UpdateCondition();
            this.UpdateSettings();
            this.UpdateSchedule();
            this.UpdateImageButtons();
        }

        /// <summary>
        /// Loads the settings so that the ControlPanel is up-to-date.
        /// </summary>
        internal void UpdateSettings()
        {
            // Modify checkboxes according to loaded setting
            if (Program.SettingsManager.StartWithWindows)
            {
                Program.ControlPanel.checkBoxOnSysStart.Checked = true;
            }
            else
            {
                Program.ControlPanel.checkBoxOnSysStart.Checked = false;
            }

            if (Program.SettingsManager.StartWithControlPanel)
            {
                Program.ControlPanel.checkBoxControlPanel.Checked = true;
            }
            else
            {
                Program.ControlPanel.checkBoxControlPanel.Checked = false;
            }

            if (Program.SettingsManager.ChangeInfo)
            {
                Program.ControlPanel.checkBoxChangeTip.Checked = true;
            }
            else
            {
                Program.ControlPanel.checkBoxChangeTip.Checked = false;
            }

            if (Program.SettingsManager.RunningInfo)
            {
                Program.ControlPanel.checkBoxRunningTip.Checked = true;
            }
            else
            {
                Program.ControlPanel.checkBoxRunningTip.Checked = false;
            }

            if (Program.SettingsManager.LoopingInfo)
            {
                Program.ControlPanel.checkBoxRepeatingTip.Checked = true;
            }
            else
            {
                Program.ControlPanel.checkBoxRepeatingTip.Checked = false;
            }

            if (Program.SettingsManager.LoopWallpapers)
            {
                Program.ControlPanel.checkBoxLoop.Checked = true;
            }
            else
            {
                Program.ControlPanel.checkBoxLoop.Checked = false;
            }
        }

        /// <summary>
        /// Restores the schedule values.
        /// </summary>
        internal void UpdateSchedule()
        {
            // Modify form depending on the current status (inactive/active)
            this.DisplayStatus();

            // Display name of the next wallpaper
            this.DisplayNextWallpaper();

            // Display remaining time
            this.DisplayChangeTime();

            if (!Program.SettingsManager.LoopWallpapers)
            {
                // Check if it is possible to set next/previous wallpaper and modify buttons
                if (Program.WallpaperManager.NextWallpaperIndex >= Program.ImageManager.Images.Count)
                {
                    this.buttonNext.Enabled = false;
                }
                else
                {
                    this.buttonNext.Enabled = true;
                }
                if (Program.WallpaperManager.PreviousWallpaperIndex < 0)
                {
                    this.buttonPrevious.Enabled = false;
                }
                else
                {
                    this.buttonPrevious.Enabled = true;
                }
            }
        }

        /// <summary>
        /// Displays/updates the current checking status.
        /// </summary>
        private void DisplayStatus()
        {
            if (Program.ChangeClient.CheckRequested)
            {
                this.labelStatus.Text = Program.LanguageManager.GetString("Status_Active");
                this.buttonStartStop.Text = Program.LanguageManager.GetString("Action_DeactivateText");
                Program.TrayApp.ContextSession.Text = Program.LanguageManager.GetString("Action_DeactivateText");
                this.progressBarTime.Visible = true;
            }
            else
            {
                this.labelStatus.Text = Program.LanguageManager.GetString("Status_Inactive");
                this.buttonStartStop.Text = Program.LanguageManager.GetString("Action_ActivateText");
                Program.TrayApp.ContextSession.Text = Program.LanguageManager.GetString("Action_Activate");
                this.progressBarTime.Visible = false;
            }
        }
        
        /// <summary>
        /// Displays/updates the name of the next wallpaper in the schedule.
        /// </summary>
        private void DisplayNextWallpaper()
        {
            string nextWallpaperPath;
            if (Program.WallpaperManager.NextWallpaperIndex < Program.ImageManager.Images.Count)
            {
                nextWallpaperPath = Program.ImageManager.Images[Program.WallpaperManager.NextWallpaperIndex];
                this.nextWallpaperValue = Path.GetFileName(nextWallpaperPath);
                this.WallpaperValue.Text = this.nextWallpaperValue;
            }
            else
            {
                // Value not available
                if (!Program.SettingsManager.LoopWallpapers)
                {
                    this.WallpaperValue.Text = Program.LanguageManager.GetString("Value_NotAvailable");
                    this.TimeValue.Text = Program.LanguageManager.GetString("Value_NotAvailable");
                }
            }
        }

        /// <summary>
        /// Displays/updates the time value in the schedule.
        /// </summary>
        private void DisplayChangeTime()
        {
            if (Program.ConditionManager.CondType == 1)
            {
                if (Program.ChangeClient.CheckRequested)
                {
                    DateTime targetTime = Program.ConditionManager.ChangeTime;
                    DateTime currentTime = DateTime.Now;

                    TimeSpan difference = currentTime - targetTime;
                    int diffHours = difference.Hours;
                    int diffMinutes = difference.Minutes;
                    int diffSeconds = difference.Seconds;

                    if (diffMinutes > 0)
                    {
                        if (diffHours > 0)
                        {
                            TimeValue.Text = diffHours + ":" + diffMinutes + ":" + diffSeconds;
                        }
                        else
                        {
                            TimeValue.Text = diffMinutes + ":" + diffSeconds;
                        }
                    }
                }
                else
                {
                    Program.ControlPanel.TimeValue.Text = Program.LanguageManager.GetString("Value_NotAvailable");
                }
            }
            else if (Program.ConditionManager.CondType == 2)
            {
                if (Program.ChangeClient.CheckRequested)
                {
                    int completeInterval = Program.ConditionManager.ChangeInterval;
                    int currentInterval = Program.ChangeClient.IntervalTimer.Interval / 1000;
                    this.TimeValue.Text = currentInterval.ToString() + Program.LanguageManager.GetString("Value_Seconds");
                    this.progressBarTime.Maximum = completeInterval;
                    this.progressBarTime.Value = currentInterval;
                }
                else
                {
                    Program.ControlPanel.TimeValue.Text = Program.LanguageManager.GetString("Value_NotAvailable");
                }
            }

        }

        /// <summary>
        /// Restores the (already loaded) condition.
        /// </summary>
        internal void UpdateCondition()
        {
            // Load old condition into form
            if (Program.ConditionManager.CondType == 1)
            {
                this.radioButtonTime.Checked = true;
                this.timePicker.Value = Program.ConditionManager.ChangeTime;
            }
            else if (Program.ConditionManager.CondType == 2)
            {
                this.radioButtonInterval.Checked = true;

                this.comboBoxInterval.SelectedIndex = Program.ConditionManager.GetIntervalIndex(Program.ConditionManager.ChangeInterval);
            }
        }

        internal void UpdateImageButtons()
        {
            // Check if the user has selected an image and modify controls
            if (this.listBoxImages.SelectedIndex == -1)
            {
                this.buttonDelete.Enabled = false;
                this.buttonDown.Enabled = false;
                this.buttonUp.Enabled = false;
                this.dropdownStyle.Enabled = false;
                this.buttonShowNow.Enabled = false;
                this.buttonPreview.Enabled = false;
            }
            else
            {
                this.buttonDelete.Enabled = true;
                this.buttonDown.Enabled = true;
                this.buttonUp.Enabled = true;
                this.dropdownStyle.Enabled = true;
                this.buttonShowNow.Enabled = true;
                this.buttonPreview.Enabled = true;
            }

            // Check if there are Images that can be deleted and modify button
            if (Program.ImageManager.Images.Count > 0)
            {
                this.buttonDeleteAll.Enabled = true;
            }
            else
            {
                this.buttonDeleteAll.Enabled = false;
            }
        }

        /// <summary>
        /// Restores the loaded images.
        /// </summary>
        internal void LoadImageList()
        {
            // Used to indicate correct position in list
            int index = 0;
            // Go through every item in image list.
            foreach (string i in Program.ImageManager.Images)
            {
                // Add current item to listbox
                this.listBoxImages.Items.Insert(index, i);
                // Next position
                index++;
            }
        }

        private void buttonStartStop_Click(object sender, EventArgs e)
        {
            // Modify start/stop button according to current session status
            if (!Program.ChangeClient.CheckRequested)
            {
                Program.ChangeClient.StartSession();
                this.UpdateSchedule();
            }
            else
            {
                Program.ChangeClient.StopSession();
                this.UpdateSchedule();
            }
        }

        private void dropdownStyle_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Save zoom style immediately if it is changed
            Program.ZoomStyleManager.SaveStyle();
        }

        private void buttonDeleteAll_Click(object sender, EventArgs e)
        {
            // Remove all images
            Program.ImageManager.RemoveAllImages();
        }

        private void checkBoxOnSysStart_CheckedChanged(object sender, EventArgs e)
        {
            // Save setting
            Program.SettingsManager.StartWithWindows = this.checkBoxOnSysStart.Checked;
        }

        private void checkBoxControlPanel_CheckedChanged(object sender, EventArgs e)
        {
            Program.SettingsManager.StartWithControlPanel = this.checkBoxControlPanel.Checked;
        }

        private void checkBoxChangeTip_CheckedChanged(object sender, EventArgs e)
        {
            Program.SettingsManager.ChangeInfo = this.checkBoxChangeTip.Checked;
        }

        private void checkBoxRunningTip_CheckedChanged(object sender, EventArgs e)
        {
            Program.SettingsManager.RunningInfo = this.checkBoxRunningTip.Checked;
        }

        private void checkBoxRepeatingTip_CheckedChanged(object sender, EventArgs e)
        {
            Program.SettingsManager.LoopingInfo = this.checkBoxRepeatingTip.Checked;
        }
    }
}
